const request = require('request-promise');

const logger = require('./logger');
const Config = require('../config/server.json');

// 获取上传属性
async function getStickerPackForm(count) {
    const url = `${Config.signal_url}/v1/sticker/pack/form/${count}`;
    const auth = 'Basic ' + Buffer.from(Config.username + ':' + Config.password).toString('base64');
    const resp = await request.get(url, { headers : { 'Authorization' : auth } });
    return JSON.parse(resp);
}

// 上传附件内容
async function uploadAttachment(form, attachment, retry) {
    let count = 0;
    const options = {
        uri: Config.cdn_url,
        timeout: 1000 * 5,
        formData: {
            'acl': form.acl,
            'key': form.key,
            'policy': form.policy,
            'Content-Type': 'application/octet-stream',
            'x-amz-algorithm': form.algorithm,
            'x-amz-credential': form.credential,
            'x-amz-date': form.date,
            'x-amz-signature': form.signature,
            'file': {
                value: attachment,
                options: {
                    filename: ''
                }
            }
        }
    };
    while (true) {
        try {
            await request.post(options);
            break;
        } catch (error) {
            count++;
            if (count > retry) {
                throw error;
            }
            logger.warn('failed to upload attachment, retrying, count: %s', count);
        }
    }
}

// 上传Sticker包
async function uploadStickerSet(bot, chatId, replyMessageId, manifest, stickerSet) {
    await bot.sendMessage(chatId, `正在获取预签名...`, {
        reply_to_message_id: replyMessageId,
    });
    const form = await getStickerPackForm(stickerSet.stickers.length);

    await bot.sendMessage(chatId, `正在上传 Manifest 文件...`, {
        reply_to_message_id: replyMessageId,
    });
    await uploadAttachment(form.manifest, manifest, 5);

    for (let idx = 0; idx < stickerSet.stickers.length; idx++) {
        const sticker = stickerSet.stickers[idx];
        await bot.sendMessage(chatId, `正在上传 Sticker 文件 [${idx+1}/${stickerSet.stickers.length}]`, {
            reply_to_message_id: replyMessageId,
        });
        await uploadAttachment(form.stickers[idx], sticker.encrypted);
    }
    return form.packId;
}

module.exports = { uploadStickerSet };
